layui.use(['table', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;

    /**
     * 入库单表管理
     */
    var StoragePut = {
        tableId: "storagePutTable"
    };
    
    /**
     * 入库单商品
     */
    var GoodsTable = {
        tableId: "goodsTable"
    };
    
    /**
     * 入库单批次
     */
    var BatchTable = {
        tableId: "batchTable"
    };

    /**
     * 入库单明细表管理
     */
    var StoragePutSingle = {
        tableId: "storagePutSingleTable"
    };

    /**
     * 初始化表格的列
     */
    StoragePut.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键'},
            {field: 'storageNumber', sort: true, title: '入库单编号'},
            {field: 'putNumber', sort: true, title: '入库订单编号'},
            {field: 'customerName', sort: true, title: '客户名称'},
            {field: 'customerNumber', sort: true, title: '客户单号'},
            {field: 'warehouseName', sort: true, title: '仓库名称'},
            {field: 'createTime', sort: true, title: '创建时间'},
        ]];
    };

    /**
     * 点击查询按钮
     */
    StoragePut.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        table.reload(StoragePut.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
                 // 搜索按钮点击事件
                 $('#btnSearch').click(function () {
                     StoragePut.search();
                 });
                 // 导出excel
                 $('#btnExp').click(function () {
                     StoragePut.exportExcel();
                 });
            }
        });
    };

    /**
     * 导出excel按钮
     */
    StoragePut.exportExcel = function () {
        var checkRows = table.checkStatus(StoragePut.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + StoragePut.tableId,
        url: Feng.ctxPath + '/storagePut/list',
        page: true,
        limit: 10,
        height: 370,
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        cols: StoragePut.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        StoragePut.search();
    });

    // 导出excel
    $('#btnExp').click(function () {
        StoragePut.exportExcel();
    });

    /**
     * 初始化商品表格的列
     */
    GoodsTable.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键id'},
            {field: 'storageNumber', hide: true, title: '入库单编号'},
            {field: 'goodsname', sort: true, title: '商品名称'},
            {field: 'goodsNumber', sort: true, title: '商品编号'},
            {field: 'putNum', sort: true, title: '应入数量'},
            {field: 'goodsId', hide: true, title: '商品id'},
        ]];
    };

    /**
     * 初始化批次表格的列
     */
    BatchTable.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键id'},
            {field: 'storageNumber', hide: true, title: '入库单编号'},
            {field: 'singleBatchnumber', sort: true, title: '批次'},
            {field: 'goodsname', sort: true, title: '商品'},
            {field: 'putNum', sort: true, title: '应入数量'},
            {field: 'detailedPutvolume', sort: true, title: '应入体积'},
            {field: 'goodsId', hide: true, title: '商品id'},
            {align: 'center', toolbar: '#tableBarBatch', title: '操作',fixed: 'right',width: 80}
        ]];
    };

    // 单击行事件(点击入库单)
    table.on('row(' + StoragePut.tableId + ')', function (obj) {
        var data = obj.data;
        goods(data);
        batch(null);
        storagePut(null);
    });
    
    function goods(data){
    	var storageNumber;
    	if (data!=null) {
    		$("#storageNumber").val(data.storageNumber);
    		storageNumber = data.storageNumber;
		} else {
			storageNumber = 'nodata';
		}
        // 渲染商品
        var tableResult = table.render({
            elem: '#' + GoodsTable.tableId,
            url: Feng.ctxPath + '/storagePutSingle/listgoods?storageNumber=' + storageNumber,
            page: true,
            limit: 10,
            height: 380,
            toolbar: '#toolbarfromGoods',
            cellMinWidth: 100,
            cols: GoodsTable.initColumn()
        });
        
        // 批量开始入库
        $('#btnStartGoods').click(function () {
        	var checkStatus = table.checkStatus('goodsTable');
            data = checkStatus.data;
            if (data.length>0) {
                var goodsIds = [];
                for (var i = 0; i < data.length; i++) {
                	goodsIds.push(data[i].goodsId);
    			}
                layer.confirm('是否开始入库选中商品?', function(index){
                	layer.close(index);
                    $.ajax({
                    	url:Feng.ctxPath + "/storagePutSingle/startGoods?goodsIds="+goodsIds+"&storageNumber="+storageNumber,
                    	cache: false,
                    	dataType:"json",
                    	beforeSend:function(){
                        	//弹出加载中
                    		index = layer.load(1, {
                                shade: [0.3,'#000'] //0.1透明度的白色背景
                            });
                    	},
                    	success:function(data){
                        	layer.close(index); 
                    		if (data.success) {
                                table.reload(StoragePut.tableId);
                                goods(null);
                                batch(null);
                                storagePut(null);
                            	Feng.success("提交成功!");
							} else {
	                            Feng.error("更新失败！" + data.message)
							}
                    	},
                    	error:function(data){
                        	layer.close(index); 
                            Feng.error("更新失败！" + data.responseJSON.message)
                    	}
                    })
                }); 
    		} else {
    			layer.alert('请至少选中一条数据');
    		}
        });
    }

    // 单击行事件(点击商品)
    table.on('row(' + GoodsTable.tableId + ')', function (obj) {
        var data = obj.data;
        batch(data);
        storagePut(null);
    });
    
    function batch(data){
    	var storageNumber;
    	var goodsId;
    	if (data!=null) {
    		$("#storageNumber").val(data.storageNumber);
    		$("#goodsId").val(data.goodsId);
    		storageNumber = data.storageNumber;
    		goodsId = data.goodsId;
		} else {
			storageNumber = 'nodata';
			goodsId = 0;
		}
        // 渲染批次
        var tableResult = table.render({
            elem: '#' + BatchTable.tableId,
            url: Feng.ctxPath + '/storagePutSingle/listbatch?storageNumber=' + storageNumber+"&goodsId="+goodsId,
            page: true,
            limit: 10,
            height: 380,
            toolbar: '#toolbarfromBatch',
            cellMinWidth: 100,
            cols: BatchTable.initColumn()
        });

        // 增加批次
        $('#addSingle').click(function () {
            layer.open({
                type: 2,
                title: '增加批次',
                area: ['1000px', '900px'],
                offset: '100px',
                anim: 5,
                content: Feng.ctxPath + '/storagePutSingle/add?storageNumber=' + $("#storageNumber").val()+"&goodsId="+goodsId,
                end: function () {
                    batch(data);
                    storagePut(null);
                }
            });
        });

        // 工具条点击事件
        table.on('tool(' + BatchTable.tableId + ')', function (obj) {
            var data2 = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'deleteBatch') {
            	BatchTable.onDeleteItem(data2);
            } 
        });

        // 删除批次按钮点击事件
        BatchTable.onDeleteItem = function (data2) {
        	layer.confirm('是否删除选中批次及其明细?', function(index){
            	layer.close(index);
                $.ajax({
                	url:Feng.ctxPath + "/storagePutSingle/deleteBatch?goodsId="+data2.goodsId+"&storageNumber="+data2.storageNumber+"&singleBatchnumber="+data2.singleBatchnumber,
                	cache: false,
                	dataType:"json",
                	beforeSend:function(){
                    	//弹出加载中
                		index = layer.load(1, {
                            shade: [0.3,'#000'] //0.1透明度的白色背景
                        });
                	},
                	success:function(data2){
                    	layer.close(index); 
                        table.reload(GoodsTable.tableId);
                        table.reload(BatchTable.tableId);
                        storagePut(null);
                    	Feng.success("删除成功!");
                	},
                	error:function(data2){
                    	layer.close(index); 
                        Feng.error("删除失败！" + data2.responseJSON.message)
                	}
                })
            }); 
        };
    }

    /**
     * 初始化明细表格的列(点击批次)
     */
    StoragePutSingle.initColumn = function () {
        return [[
            {type: 'checkbox',fixed: 'left'},
            {field: 'id', hide: true, title: '主键id',fixed: 'left'},
            {field: 'positionNumber', sort: true, title: '库位编号', unresize: true, totalRowText: '合计：',width: 170,fixed: 'left'},
            {field: 'trayNumber', sort: true, title: '托盘编号'},
            {field: 'goodsname', sort: true, title: '商品名称'},
            {field: 'goodsNumber', sort: true, title: '商品编号'},
            {field: 'putBalenum', sort: true, title: '应入大包数', totalRow: true},
            {field: 'putNum', sort: true, title: '应入数量', totalRow: true},
            {field: 'singleBatchnumber', sort: true, title: '批号'},
            {field: 'recommend', sort: true, title: '入库批次'},
            {field: 'singleState', sort: true, title: '入库状态'},
            {align: 'center', toolbar: '#tableBarSingle', title: '操作',fixed: 'right',width: 120}
        ]];
    };

    // 单击行事件
    table.on('row(' + BatchTable.tableId + ')', function (obj) {
        var data = obj.data;
        storagePut(data);
    });
    
    function storagePut(data){
    	var singleBatchnumber;
    	var goodsId;
    	if (data!=null) {
    		$("#singleBatchnumber").val(data.singleBatchnumber);
    		$("#goodsId").val(data.goodsId);
    		singleBatchnumber = data.singleBatchnumber;
    		goodsId = data.goodsId;
		} else {
			singleBatchnumber = 'nodata';
			goodsId = 0;
		}
        // 渲染商品明细表格
        var tableResult = table.render({
            elem: '#' + StoragePutSingle.tableId,
            url: Feng.ctxPath + '/storagePutSingle/list?storageNumber=' + $("#storageNumber").val()+"&goodsId="+goodsId+"&singleBatchnumber="+singleBatchnumber,
            page: true,
            limit: 50,
            height: 380,
            toolbar: '#toolbarfromSingle',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: StoragePutSingle.initColumn()
        });
        
        // 批量分配库位
        $('#pointsPosition').click(function () {	
        	var checkStatus = table.checkStatus('storagePutSingleTable');
            data2 = checkStatus.data;
            if (data2.length>0) {
                var ids = [];
                for (var i = 0; i < data2.length; i++) {
                	ids.push(data2[i].id);
    			}
                layer.open({
                    type: 2,
                    title: '批量分配库位',
                    area: ['800px', '500px'],
                    offset: '100px',
                    anim: 5,
                    content: Feng.ctxPath + '/storagePutSingle/toPointsPosition?ids=' + ids+"&storageNumber=" + $("#storageNumber").val(),
                    end: function () {
                    	storagePut(data);
                    }
                });
    		} else {
    			layer.alert('请至少选中一条数据');
    		}
        });

        // 工具条点击事件
        table.on('tool(' + StoragePutSingle.tableId + ')', function (obj) {
            var data2 = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'editSingle') {
            	StoragePutSingle.openEditDlg(data2);
            } else if (layEvent === 'deleteSingle') {
            	StoragePutSingle.onDeleteItem(data2);
            }
        });

        // 修改按钮点击事件
        StoragePutSingle.openEditDlg = function (data2) {
            layer.open({
                type: 2,
                title: '明细修改',
                area: ['1000px', '900px'],
                offset: '100px',
                anim: 5,
                content: Feng.ctxPath + '/storagePutSingle/edit?id='+data2.id,
                end: function () {
                	storagePut(data);
                }
            });
        };

        // 删除按钮点击事件
        StoragePutSingle.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/storagePutSingle/delete", function (data2) {
                    Feng.success("删除成功!");
                    storagePut(data);
                }, function (data) {
                    Feng.error("删除失败!" + data2.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("是否删除?", operation);
        };
    }
    
    
    
});
